package com.city.parking;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.InfoWindowAdapter;
import com.amap.api.maps.AMap.OnCameraChangeListener;
import com.amap.api.maps.AMap.OnMapClickListener;
import com.amap.api.maps.AMap.OnMapLongClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.overlay.PoiOverlay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.amap.api.services.poisearch.PoiSearch.OnPoiSearchListener;
import com.amap.api.services.poisearch.PoiSearch.SearchBound;
import com.city.parking.ParkingPopup.OnParkingClickListener;
import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;
import com.city.parking.util.SharePrefUtil;
import com.city.parking.util.Utils;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup.OnCheckedChangeListener;

public class GdMapFragment extends Fragment implements OnClickListener, OnCameraChangeListener,
		DrawerListener, LocationSource, AMapLocationListener, OnPoiSearchListener,
		OnParkingClickListener, OnMapClickListener {

	private MapView mMapView;
	private AMap aMap;
	// 定位相关
	private AMapLocationClient mLocClient;
	private AMapLocationClientOption mLocationOption;
	private OnLocationChangedListener mListener;
	private UiSettings mUiSettings;
	private PoiSearch.Query query;// Poi查询条件类
	private LatLonPoint lp = new LatLonPoint(39.908127, 116.375257);// 默认西单广场
	private BitmapDescriptor mCurrentMarker;
	private Activity mActivity;
	private final int DEFAULT_ZOOM_LEVEL = 17;
	private float curZoomLevel = 0;

	private final int ORDER_PRICE = 1;
	private final int ORDER_IDLE = 2;
	private int mOrderType = ORDER_IDLE;
	private int mSearchArea = 1000;
	private int mSearchRetCnt = 0;
	private final int MAX_SEARCH_RET_CNT = 2;

	// UI相关
	private OnCheckedChangeListener radioButtonListener;
	private ImageButton requestLocButton, parkingTypeButton,
			parkingFilterButton, parkingFindButton, parkingRmbrButton;
	private ImageView navCenter;
	private boolean isFirstLoc = true;// 是否首次定位
	private boolean signParking = false;
	private PoiSearch mPoiSearch;
	//private PoiNearbySearchOption mPoiSearchOption;
	//private RoutePlanSearch mRoutePlan = null; // 搜索模块，也可去掉地图模块独立使用
	private int nodeIndex = -1;// 节点索引,供浏览节点时使用
	//private RouteLine route = null;
	//private OverlayManager routeOverlay = null;
	private ParkingPopup mParkingPopup;
	private BitmapDescriptor mDestMarkBmp = BitmapDescriptorFactory
			.fromResource(R.drawable.dest_mark_loction);;
	private MarkerOptions mDestMark = null;
	private BitmapDescriptor mDestRmbrBmp = BitmapDescriptorFactory
			.fromResource(R.drawable.ico_car_location);
	private ParkingOverlayManager mPom = null;
	private Point left = null;
	private Point right = null;
	private int ViewWidth = 0;

	private static GdMapFragment instance = null;
	private TextView makerTV = null;
	private TextView bigMakerTV = null;

	public static GdMapFragment getInstance() {
		return instance;
	}

	public static boolean instanced() {
		return instance != null;
	}
	
	/**
	 * 定位成功后回调函数
	 */
	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		if (mListener != null && amapLocation != null) {
			if (amapLocation != null
					&& amapLocation.getErrorCode() == 0) {
				mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
				
				if (isFirstLoc) {
					isFirstLoc = false;
					moveToLocation(amapLocation, DEFAULT_ZOOM_LEVEL);
					ParkingApp.get().mCurCity = amapLocation.getCity();
					Utils.log("我的坐标：" + amapLocation.getCity());

					LatLng ll = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
					searchNearParks(ll);
				}
			} else {
				String errText = "定位失败," + amapLocation.getErrorCode()+ ": " + amapLocation.getErrorInfo();
				ParkingApp.showToast(errText);
			}
		}
	}
	
	/**
	 * 设置一些amap的属性
	 */
	private void setUpMap() {
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
		// 设置定位的类型为定位模式 ，可以由定位、跟随或地图根据面向方向旋转几种
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
	}

	private void moveToLocation(AMapLocation location, int zoom) {
		LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
		moveToLocation(ll, zoom);
	}
	
	private void moveToLocation(LatLng ll, int zoom) {
		CameraUpdate u = CameraUpdateFactory.newLatLngZoom(ll, zoom);
		aMap.animateCamera(u);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActivity = this.getActivity();

		View view = inflater.inflate(R.layout.gd_map_frame, container, false);
		requestLocButton = (ImageButton) view.findViewById(R.id.locate_btn);
		requestLocButton.setOnClickListener(this);
		parkingTypeButton = (ImageButton) view
				.findViewById(R.id.parking_type_btn);
		parkingTypeButton.setOnClickListener(this);
		parkingRmbrButton = (ImageButton) view
				.findViewById(R.id.parking_rmbr_btn);
		parkingRmbrButton.setOnClickListener(this);
		parkingFilterButton = (ImageButton) view
				.findViewById(R.id.filter_parking_btn);
		//parkingFilterButton.setOnClickListener(this);
		parkingFilterButton.setVisibility(View.GONE);
		parkingFindButton = (ImageButton) view
				.findViewById(R.id.find_parking_btn);
		//parkingFindButton.setOnClickListener(this);
		parkingFindButton.setVisibility(View.GONE);
		navCenter = (ImageView) view.findViewById(R.id.nav_ico_center);
		navCenter.setOnClickListener(this);
		LinearLayout ll = (LinearLayout) view.findViewById(R.id.ll_where_go);
		ll.setOnClickListener(this);
		View scan = view.findViewById(R.id.nav_ico_scanning);
		scan.setOnClickListener(this);

		if (signParking)
			parkingTypeButton.setImageResource(R.drawable.ico_all);
		else
			parkingTypeButton.setImageResource(R.drawable.ico_sign);

		// 地图初始化
		mMapView = (MapView) view.findViewById(R.id.gmapView);
		mMapView.onCreate(savedInstanceState);// 此方法必须重写
		
		aMap = mMapView.getMap();
		// 开启定位图层
		aMap.setLocationSource(this);// 设置定位监听
		aMap.setMyLocationEnabled(true);
		aMap.setMyLocationType(AMap.LOCATION_TYPE_LOCATE);
		//aMap.setMapStatus(MapStatusUpdateFactory.zoomTo(17));
		aMap.animateCamera(CameraUpdateFactory.zoomTo(17));
		//aMap.setOnMapStatusChangeListener(this);
		aMap.setOnCameraChangeListener(this);
		
		aMap.setOnMapClickListener(this);

		mUiSettings = aMap.getUiSettings();
		mUiSettings.setMyLocationButtonEnabled(true);// 设置默认定位按钮是否显示
		mUiSettings.setZoomControlsEnabled(false);
		mUiSettings.setScaleControlsEnabled(false);

		mSearchArea = SharePrefUtil.getSearchRadius(1000);
		
		query = new PoiSearch.Query("停车", "", "");// 第一个参数表示搜索字符串，第二个参数表示poi搜索类型，第三个参数表示poi搜索区域（空字符串代表全国）
		query.setPageSize(mSearchArea / 250 + 10);
		mPoiSearch = new PoiSearch(mActivity, query);
		mPoiSearch.setOnPoiSearchListener(this);

		instance = this;

		double last_lat = SharePrefUtil.getLastLatitude();
		double last_lng = SharePrefUtil.getLastLongitude();
		if (last_lat > 0 && last_lng > 0) {
			moveToLocation(new LatLng(last_lat, last_lng), DEFAULT_ZOOM_LEVEL);
		}

		mPom = new ParkingOverlayManager(aMap);
		aMap.setOnMarkerClickListener(mPom);
		aMap.setInfoWindowAdapter(mPom);

		initMarkerView(inflater);
		return view;
	}
	
	private void initMarkerView(LayoutInflater inflater) {
		View mt = inflater.inflate(R.layout.maker_template, null);
		makerTV = (TextView) mt.findViewById(R.id.maker_content);
		makerTV.setBackgroundResource(R.drawable.ico_park_green);
		makerTV.setDrawingCacheEnabled(true);
		makerTV.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		makerTV.layout(0, 0, makerTV.getMeasuredWidth(),
				makerTV.getMeasuredHeight());
		
		View bmt = inflater.inflate(R.layout.big_maker_template, null);
		bigMakerTV = (TextView) bmt.findViewById(R.id.big_maker_content);
		bigMakerTV.setBackgroundResource(R.drawable.ico_park_green_big);
		bigMakerTV.setDrawingCacheEnabled(true);
		bigMakerTV.measure(View.MeasureSpec.makeMeasureSpec(0,
				View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
				.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
		bigMakerTV.layout(0, 0, bigMakerTV.getMeasuredWidth(),
				bigMakerTV.getMeasuredHeight());
	}

	private String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(
				Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}

	private boolean mIsEngineInitSuccess = false;
//	private NaviEngineInitListener mNaviEngineInitListener = new NaviEngineInitListener() {
//		public void engineInitSuccess() {
//			mIsEngineInitSuccess = true;
//		}
//
//		public void engineInitStart() {
//		}
//
//		public void engineInitFail() {
//			Toast.makeText(mActivity, "engineInitFail", Toast.LENGTH_LONG)
//					.show();
//		}
//	};

	@Override
	public void onPause() {
		super.onPause();
		// activity 暂停时同时暂停地图控件
		mMapView.onPause();

		AMapLocation location = mLocClient.getLastKnownLocation();
		if (location == null)
			return;
		SharePrefUtil.setLastLatitude((float) location.getLatitude());
		SharePrefUtil.setLastLongitude((float) location.getLongitude());
		ParkingApp.get().hideProgressBar();
	}

	@Override
	public void onResume() {
		super.onResume();
		// activity 恢复时同时恢复地图控件
		mMapView.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// activity 销毁时同时销毁地图控件
		mMapView.onDestroy();
		mLocClient.stopLocation();
		instance = null;
	}

	private LatLng mSearchCenter;
	private void searchNearParks(LatLng center) {
		mSearchRetCnt = 0;
		mSearchCenter = center;
		mPom.reset();
		if (!signParking) {
			lp.setLatitude(center.latitude);
			lp.setLongitude(center.longitude);
			mPoiSearch.setBound(new SearchBound(lp, mSearchArea, true));//
			// 设置搜索区域为以lp点为圆心，其周围2000米范围
			/*
			 * List<LatLonPoint> list = new ArrayList<LatLonPoint>();
			 * list.add(lp);
			 * list.add(AMapUtil.convertToLatLonPoint(Constants.BEIJING));
			 * poiSearch.setBound(new SearchBound(list));// 设置多边形poi搜索范围
			 */
			mPoiSearch.searchPOIAsyn();// 异步搜索
		}
		getNearParkings(center, mSearchArea);

		ParkingApp.get().showProgressBar(mActivity);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.locate_btn:
			moveToLocation(mLocClient.getLastKnownLocation(), 17);
			break;
		case R.id.parking_type_btn:
			signParking = !signParking;
			if (signParking) {
				parkingTypeButton.setImageResource(R.drawable.ico_all);
				ParkingApp.showToast("只显示合作停车场");
			} else {
				parkingTypeButton.setImageResource(R.drawable.ico_sign);
			}
//			searchNearParks(mBaiduMap.getMapStatus().target);
			searchNearParks(aMap.getCameraPosition().target);
			break;
		case R.id.nav_ico_center:
			((MainActivity) mActivity).openSideMenu();
			break;
		case R.id.ll_where_go:
			Intent i = new Intent(mActivity, SearchActivity.class);
			startActivityForResult(i, ParkingApp.RQST_CODE_SEARCH);

			break;
		case R.id.nav_ico_scanning:
			Intent i2 = new Intent(mActivity, ParkingScanActivity.class);
			startActivityForResult(i2, ParkingApp.RQST_CODE_SCAN);
			break;
		case R.id.parking_rmbr_btn:
			Intent i3 = new Intent(mActivity, MyParkingsActivity.class);
			startActivityForResult(i3, ParkingApp.RQST_CODE_FAVOR);
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (resultCode != Activity.RESULT_OK)
			return;
		if (requestCode == ParkingApp.RQST_CODE_SEARCH) {
			Bundle data = intent.getExtras();
			double lat = data.getDouble("lat");
			double lng = data.getDouble("lng");
			LatLng ll = new LatLng(lat, lng);
			mDestMark = new MarkerOptions().position(ll).icon(mDestMarkBmp)
					.zIndex(-1).draggable(true);
//			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
//			mBaiduMap.animateMapStatus(u);
			CameraUpdate u = CameraUpdateFactory.newLatLng(ll);
			aMap.animateCamera(u);

			searchNearParks(ll);
		} else if (requestCode == ParkingApp.RQST_CODE_SCAN) {
			Bundle data = intent.getExtras();
			String result = data.getString("result");
			Utils.log("result = " + result);
			ParkingApp.showToast("result = " + result);
		} else if (requestCode == ParkingApp.RQST_CODE_FAVOR) {
			ParkingItem item = intent.getParcelableExtra("item");
			gotoRmbrParking(item.latitude, item.longitude, item.name, item.addr);
		} else if (requestCode == ParkingApp.RQST_CODE_REPORT) {
			String name = intent.getStringExtra("name");
			double lat = intent.getDoubleExtra("lat", -1);
			double lng = intent.getDoubleExtra("lng", -1);
			if (name == null || name.equals(""))
				name = "Unkown";
			LatLng ll = new LatLng(lat, lng);
			mDestMark = new MarkerOptions().position(ll).icon(mDestMarkBmp).zIndex(-1).title(name);
//			mBaiduMap.addOverlay(mDestMark);
			aMap.addMarker(mDestMark);
		}
	}

	private void gotoRmbrParking(double lat, double lng, String name, String addr) {
//		mBaiduMap.clear();
		aMap.clear();

		LatLng ll = new LatLng(lat, lng);
//		MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
//		mBaiduMap.animateMapStatus(u);
//		mBaiduMap.setMapStatus(MapStatusUpdateFactory.zoomTo(DEFAULT_ZOOM_LEVEL));
		CameraUpdate u = CameraUpdateFactory.newLatLng(ll);
		aMap.animateCamera(u);
		
		MarkerOptions mo = new MarkerOptions().position(ll).icon(mDestRmbrBmp);
//		mBaiduMap.addOverlay(mo);
		aMap.addMarker(mo);

		return;
	}

	private class ParkingOverlayManager implements  OnMarkerClickListener, InfoWindowAdapter{
		private AMap aMap;
		
		public ParkingOverlayManager(AMap map) {
			aMap = map;
		}

		private PoiResult result;
		private ArrayList<ParkingItem> ourParks;
		private final int GAODE = 1;
		private final int NINEBIT = 2;
		private final int NINEBIT_SHIFT = 10000;
		private int type = 1;
		private boolean baiduAdded = false;
		private boolean OurAdded = false;
//		private ArrayList<MarkerOptions> ops = new ArrayList<MarkerOptions>();
		private ArrayList<MarkerOptions> gd_marker = new ArrayList<MarkerOptions>();
		private ArrayList<MarkerOptions> our_marker = new ArrayList<MarkerOptions>();
		private Marker lastMarker = null;
		private MarkerOptions lastMo = null;

		public void setResult(PoiResult result) {
			type = GAODE;
			baiduAdded = false;
			this.result = result;
		}
		
		public void setResult2(ArrayList<ParkingItem> parks) {
			type = NINEBIT;
			OurAdded = false;
			this.ourParks = parks;
		}
		
		public void reset() {
			lastMarker = null;
			lastMo = null;
		}
		
		public void hideInfoWindow() {
			if (lastMarker != null)
				lastMarker.hideInfoWindow();
		}

		@Override
		public View getInfoContents(Marker arg0) {
			// TODO Auto-generated method stub
			return mParkingPopup.getView();
		}

		@Override
		public View getInfoWindow(Marker arg0) {
			// TODO Auto-generated method stub
			return mParkingPopup.getView();
		}

		@Override
		public boolean onMarkerClick(Marker marker) {
			int idx = (int)marker.getZIndex();
			Utils.log("click idx=" + idx);
			if (idx < 0) {
				if (marker.getTitle() != null && !marker.getTitle().equals("")) {
					Toast.makeText(mActivity, marker.getTitle(), Toast.LENGTH_SHORT).show();
				}
				return true;
			}

			ParkingItem park;
			BitmapDescriptor bd;
			if (idx < NINEBIT_SHIFT) {
				PoiItem poi = result.getPois().get(idx);
				park = new ParkingItem(poi);
				bd = BitmapDescriptorFactory.fromResource(R.drawable.ico_park_big);
			} else {
				park = ourParks.get(idx - NINEBIT_SHIFT);
				if (park.portLeftCount<10)
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_red_big);
				else if (park.portLeftCount < 20)
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_yellow_big);
				else
					bigMakerTV.setBackgroundResource(R.drawable.ico_park_green_big);

				if (park.portLeftCount > 999)
					bigMakerTV.setText("999");
				else
					bigMakerTV.setText("" + park.portLeftCount);
				bigMakerTV.buildDrawingCache();
				Bitmap b = Bitmap.createBitmap(bigMakerTV.getDrawingCache());
				bd = BitmapDescriptorFactory.fromBitmap(b);
			}
			
			if (lastMo != null) {
				lastMarker.remove();
				BitmapDescriptor lbd = BitmapDescriptorFactory.fromResource(R.drawable.ico_park);
				lastMo.icon(lbd);
				aMap.addMarker(lastMo);
			}
			
			AMapLocation bl = mLocClient.getLastKnownLocation();
			LatLng cl = new LatLng(bl.getLatitude(), bl.getLongitude());
			int distance = (int)AMapUtils.calculateLineDistance(park.positionGD(), cl) ;
			mParkingPopup = new ParkingPopup(mActivity); // must be new one
			mParkingPopup.bindPark(park, distance);
			mParkingPopup.setOnParkingClickListener(instance);
			
			MarkerOptions mo = getMarkerOption(idx);
			mo.icon(bd);
			marker.remove();
			Marker nm = aMap.addMarker(mo);
			nm.showInfoWindow();

			lastMarker = nm;
			lastMo = mo;

			return true;
		}
		
		public MarkerOptions getMarkerOption(int idx) {
			if (idx < NINEBIT_SHIFT && idx < gd_marker.size()) {
				return gd_marker.get(idx);
			} else if (idx >= NINEBIT_SHIFT && idx - NINEBIT_SHIFT < our_marker.size()) {
				return our_marker.get(idx - NINEBIT_SHIFT);
			}
			
			return null;
		}

		public void addToMap() {
			if (type == GAODE && !baiduAdded) {
//				List<PoiInfo> pois = result.getAllPoi();
				List<PoiItem> pois = result.getPois();
				BitmapDescriptor bd = BitmapDescriptorFactory.fromResource(R.drawable.ico_park);
				gd_marker.clear();
				for (int i = 0; i < pois.size(); i++) {
					MarkerOptions mo = new MarkerOptions();
					LatLonPoint llp = pois.get(i).getLatLonPoint();
					LatLng ll = new LatLng(llp.getLatitude(), llp.getLongitude());
					mo.position(ll);
					mo.icon(bd);
					mo.anchor(0.5f, 1);
					mo.title("park");
					mo.zIndex(i); // must to be set
					gd_marker.add(mo);
				}
				baiduAdded = true;
				aMap.addMarkers(gd_marker, false);
			} else if (type == NINEBIT && ourParks != null && !OurAdded) {
				int i = NINEBIT_SHIFT;
				our_marker.clear();
				for (ParkingItem park : ourParks) {
					int distance = (int)AMapUtils.calculateLineDistance(park.positionGD(), mSearchCenter) ;

					Utils.log(park.name + " = " + distance + "m");
					if (distance > mSearchArea || park.isDeleted == 1) {
						Utils.log("skip");
						continue;
					}

					MarkerOptions mo = new MarkerOptions();
					mo.position(park.positionGD());
					if (park.portLeftCount<10)
						makerTV.setBackgroundResource(R.drawable.ico_park_red);
					else if (park.portLeftCount < 20)
						makerTV.setBackgroundResource(R.drawable.ico_park_yellow);
					else
						makerTV.setBackgroundResource(R.drawable.ico_park_green);

					if (park.portLeftCount > 999)
						makerTV.setText("999");
					else
						makerTV.setText("" + park.portLeftCount);
					makerTV.buildDrawingCache();
					Bitmap b = Bitmap.createBitmap(makerTV.getDrawingCache());
					BitmapDescriptor bd = BitmapDescriptorFactory.fromBitmap(b);
					mo.icon(bd);
					mo.anchor(0.5f, 1);
					mo.zIndex(i++);
					mo.title("park");
					our_marker.add(mo);
				}
				OurAdded = true;
				aMap.addMarkers(our_marker, false);
			}
		}
	}

	@Override
	public void onDrawerClosed(View arg0) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDrawerOpened(View arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDrawerSlide(View arg0, float arg1) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onDrawerStateChanged(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onParkingClick(ParkingItem park) {
		// TODO Auto-generated method stub

		//startCalcRoute(park);
		
        Intent i = new Intent(mActivity, GdBasicNaviActivity.class);
        AMapLocation al = mLocClient.getLastKnownLocation();
        LatLng start = new LatLng(al.getLatitude(), al.getLongitude());
        Bundle r = new Bundle();
        r.putParcelable("start", start);
        r.putParcelable("end", park.positionGD());
        i.putExtra("route", r);
        
        startActivity(i);
	}

	@Override
	public void onParkingDescClick(ParkingItem park) {
		// TODO Auto-generated method stub
		Intent i = new Intent(mActivity, ParkingDetailActivity.class);
		i.putExtra("park", park);
		startActivity(i);
	}

	private final int NEAR_PARK = 1;

	private void getNearParkings(LatLng ll, int radius) {
		JSONObject json = new JSONObject();
		try {
			json.put("longitude", ll.longitude);
			json.put("latitude", ll.latitude);
			json.put("radius", radius);
		} catch (JSONException e1) {
			e1.printStackTrace();
			return;
		}
		HttpRequest req = new HttpRequest(ParkingApp.url_get_near_park, NEAR_PARK, json.toString(), handler);
		HttpClientUtil.post(req);
	}

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			ParkingApp.get().hideProgressBar();
			if (msg.arg1 == HttpRequest.NET_SUCCESS) {
				HttpResult ret = (HttpResult) msg.obj;
				if (ret != null && ret.status == HttpResult.STATUS_SUCCESS) {
					ArrayList<ParkingItem> parks = ParkingItem.fromJsonArray(ret.body);

					if (mSearchRetCnt++ == 0) {
						aMap.clear();
						if (mDestMark != null)
							aMap.addMarker(mDestMark);
					}

					mPom.setResult2(parks);
					mPom.addToMap();
//					if ((mSearchRetCnt >= MAX_SEARCH_RET_CNT || signParking) && ViewWidth < mSearchArea*2) {
//						mPom.zoomToSpan();
//					}
					return;
				}
			}
			Utils.log("九比特服务器异常");
		}
	};

	private OnMapLongClickListener longMapClickListener = new OnMapLongClickListener() {  
	    /** 
	    * 地图长按事件监听回调函数 
	    * @param point 长按的地理坐标 
	    */  
	    public void onMapLongClick(LatLng point){
			Intent i = new Intent(mActivity, ReportLocationActivity.class);
	        Bundle bundle = new Bundle();				//创建Bundle对象
	        bundle.putDouble("lat", point.latitude);	//装入数据
	        bundle.putDouble("lng", point.longitude);	//装入数据
	        i.putExtras(bundle);
			startActivityForResult(i, ParkingApp.RQST_CODE_REPORT);
	    }  
	};

	@Override
	public void activate(OnLocationChangedListener listener) {
		// TODO Auto-generated method stub
		mListener = listener;
		if (mLocClient == null) {
			mLocClient = new AMapLocationClient(mActivity);
			mLocationOption = new AMapLocationClientOption();
			//设置定位监听
			mLocClient.setLocationListener(this);
			//设置为高精度定位模式
			mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);
			//设置定位参数
			mLocClient.setLocationOption(mLocationOption);
			// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
			// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
			// 在定位结束后，在合适的生命周期调用onDestroy()方法
			// 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
			mLocClient.startLocation();
		}
	}

	@Override
	public void deactivate() {
		// TODO Auto-generated method stub
		mListener = null;
		if (mLocClient != null) {
			mLocClient.stopLocation();
			mLocClient.onDestroy();
		}
		mLocClient = null;
	}
	
	/**
	 * 对移动地图结束事件回调
	 */
	@Override
	public void onCameraChangeFinish(CameraPosition status) {
		if (mSearchCenter == null)
			return;
		
		Utils.log("onMapStatusChangeFinish center="+status.target+",radius="+mSearchArea);
		double distance = AMapUtils.calculateLineDistance(status.target, mSearchCenter);
		if (distance > mSearchArea/2)
			searchNearParks(status.target);
		else
			Utils.log("distance <= MIN_RESEACH_DISTANCE");

		if (curZoomLevel != status.zoom) {
			curZoomLevel = status.zoom;			
			if (left == null)
				left = new Point(0, mMapView.getHeight());
			if (right == null)
				right = new Point(mMapView.getWidth(), mMapView.getHeight());
			LatLng latlng1 = aMap.getProjection().fromScreenLocation(left);
			LatLng latlng2 = aMap.getProjection().fromScreenLocation(right);
			ViewWidth = (int) AMapUtils.calculateLineDistance(latlng1, latlng2);
			
			if (ViewWidth <= 1000)
				mSearchArea = 500;
			else if (ViewWidth < 2000)
				mSearchArea = 1000;
			else
				mSearchArea = 2500;
			
			Utils.log("zoom level changed, ViewWidth="+ViewWidth+",mSearchArea="+mSearchArea);
		}
	}

	@Override
	public void onCameraChange(CameraPosition arg0) {
		// TODO Auto-generated method stub
		
	}
	private PoiResult poiResult; // poi返回的结果
	private List<PoiItem> poiItems;// poi数据
	
	@Override
	public void onPoiSearched(PoiResult result, int rCode) {
		// TODO Auto-generated method stub
		ParkingApp.get().hideProgressBar();
		// TODO Auto-generated method stub
		if (result == null || rCode != 0) {
			Utils.log("没有找到停车场，修改条件后再试试吧");
			return;
		}
//		if (result.error == SearchResult.ERRORNO.NO_ERROR) {
			if (mSearchRetCnt++ == 0) {
				aMap.clear();
			}

			if (mDestMark != null)
				aMap.addMarker(mDestMark);
			
			mPom.setResult(result);
			mPom.addToMap();
	}

	@Override
	public void onMapClick(LatLng arg0) {
		// TODO Auto-generated method stub
		mPom.hideInfoWindow();
	}

}
